package com.songqi.common.mybatis.core.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.songqi.common.security.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;

import java.util.Date;

/**
 * 通用参数填充实现类
 *
 * 如果没有显式的对通用参数进行赋值，这里会对通用参数进行填充、赋值
 *
 * @author songqi(13776346982)
 */
@Slf4j
public class DefaultMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        try{
            Object createBy = getFieldValByName("createBy", metaObject);
            if (createBy == null) {
                this.setFieldValByName("createBy", SecurityUtils.getUsername(), metaObject);
            }
            Object updateBy = getFieldValByName("updateBy", metaObject);
            if(updateBy == null){
                this.setFieldValByName("updateBy", SecurityUtils.getUsername(), metaObject);
            }
        } catch (Exception e){
            log.error(e.getMessage(), e);
        }
        this.setFieldValByName("createTime", new Date(), metaObject);
        this.setFieldValByName("updateTime", new Date(), metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        try{
            Object updateBy = getFieldValByName("updateBy", metaObject);
            if(updateBy == null){
                this.setFieldValByName("updateBy", SecurityUtils.getUsername(), metaObject);
            }
        } catch (Exception e){
            log.error(e.getMessage(), e);
        }
        this.setFieldValByName("updateTime", new Date(), metaObject);
    }
}
